Coursework 1: Image filtering¶
In this coursework you will practice techniques for image filtering. The coursework includes coding questions and written questions. Please read both the text and the code in this notebook to get an idea what you are expected to implement.
What to do?¶
Complete and run the code using
jupyter-laborjupyter-notebookto get the results.Export (File | Save and Export Notebook As...) the notebook as a PDF file, which contains your code, results and answers, and upload the PDF file onto Scientia.
Instead of clicking the Export button, you can also run the following command instead:
jupyter nbconvert coursework_01_solution.ipynb --to pdfIf Jupyter complains about some problems in exporting, it is likely that pandoc (https://pandoc.org/installing.html) or latex is not installed, or their paths have not been included. You can install the relevant libraries and retry. Alternatively, use the Print function of your browser to export the PDF file.
If Jupyter-lab does not work for you at the end (we hope not), you can use Google Colab to write the code and export the PDF file.
Dependencies:¶
You need to install Jupyter-Lab (https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html) and other libraries used in this coursework, such as by running the command:
pip3 install [package_name]
# Import libaries (provided)
import imageio.v3 as imageio
import numpy as np
import matplotlib.pyplot as plt
import noise
import scipy
import scipy.signal
import math
import time
1. Moving average filter (20 points).¶
Read the provided input image, add noise to the image and design a moving average filter for denoising.
You are expected to design the kernel of the filter and then perform 2D image filtering using the function scipy.signal.convolve2d().
# Read the image (provided)
image = imageio.imread('campus_snow.jpg')
plt.imshow(image, cmap='gray')
plt.gcf().set_size_inches(8, 8)
# Corrupt the image with Gaussian noise (provided)
image_noisy = noise.add_noise(image, 'gaussian')
plt.imshow(image_noisy, cmap='gray')
plt.gcf().set_size_inches(8, 8)
# Design the filter h
### Insert your code ###
h = np.ones((3,3))
# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h, "full", "symm")
# Print the filter (provided)
print('Filter h:')
print(h)
# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h: [[1. 1. 1.] [1. 1. 1.] [1. 1. 1.]]
1.2 Filter the noisy image with a 11x11 moving average filter.¶
# Design the filter h
### Insert your code ###
h = np.ones((11,11))
# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_filtered = scipy.signal.convolve2d(image_noisy, h, "full", "symm")
# Print the filter (provided)
print('Filter h:')
print(h)
# Display the filtering result (provided)
plt.imshow(image_filtered, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h: [[1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] [1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
1.3 Comment on the filtering results. How do different kernel sizes influence the filtering results?¶
Increasing the kernel size increases the smoothing of the signal.
2. Edge detection (56 points).¶
Perform edge detection using Sobel filtering, as well as Gaussian + Sobel filtering.
2.1 Implement 3x3 Sobel filters and convolve with the noisy image.¶
# Design the filters
### Insert your code ###
sobel_x = np.array([[1,0,-1],[2,0,-2],[1,0,-1]])
sobel_y = sobel_x.T
# Image filtering
grad_x = scipy.signal.convolve2d(image_noisy, sobel_x)
grad_y = scipy.signal.convolve2d(image_noisy, sobel_y)
# Calculate the gradient magnitude
grad_mag = np.sqrt(grad_x**2 + grad_y**2)
# Print the filters (provided)
print('sobel_x:')
print(sobel_x)
print('sobel_y:')
print(sobel_y)
# Display the magnitude map (provided)
plt.imshow(grad_mag, cmap='gray')
plt.gcf().set_size_inches(8, 8)
sobel_x: [[ 1 0 -1] [ 2 0 -2] [ 1 0 -1]] sobel_y: [[ 1 2 1] [ 0 0 0] [-1 -2 -1]]
2.2 Implement a function that generates a 2D Gaussian filter given the parameter $\sigma$.¶
# Design the Gaussian filter
def gaussian_filter_2d(sigma, k=3):
# sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
#
# return: a 2D array for the Gaussian kernel
sigma_sqr = sigma**2
constant = 1/(2*math.pi*sigma_sqr)
kernel_size = math.ceil(sigma)*k*2 + 1
h = np.zeros((kernel_size, kernel_size))
for i in range(0 - math.ceil(sigma)*k, kernel_size - math.ceil(sigma)*k):
for j in range(0 - math.ceil(sigma)*k, kernel_size - math.ceil(sigma)*k):
h[i+math.ceil(sigma)*k,j+math.ceil(sigma)*k] = constant * math.pow(math.e, (i**2+j**2)/(-2*sigma_sqr))
return h
# Visualise the Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)
plt.imshow(h)
<matplotlib.image.AxesImage at 0x25e81230c50>
2.3 Perform Gaussian smoothing ($\sigma$ = 5 pixels) and evaluate the computational time for Gaussian smoothing. After that, perform Sobel filtering and show the gradient magintude map.¶
# Construct the Gaussian filter
h = gaussian_filter_2d(5)
# Perform Gaussian smoothing and count time
start = time.time()
image_filtered = scipy.signal.convolve2d(image_noisy, h)
print("Time taken: ", time.time()-start)
# Image filtering
grad_x = scipy.signal.convolve2d(image_filtered, sobel_x)
grad_y = scipy.signal.convolve2d(image_filtered, sobel_y)
# Calculate the gradient magnitude
grad_mag = np.sqrt(grad_x**2 + grad_y**2)
# Display the gradient magnitude map (provided)
plt.imshow(grad_mag, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
Time taken: 2.6581950187683105
2.4 Implement a function that generates a 1D Gaussian filter given the parameter $\sigma$. Generate 1D Gaussian filters along x-axis and y-axis respectively.¶
# Design the Gaussian filter
def gaussian_filter_1d(sigma, k=3):
# sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
#
# return: a 1D array for the Gaussian kernel
sigma_sqr = sigma**2
constant = 1/(math.sqrt(2*math.pi)*sigma)
kernel_size = math.ceil(sigma)*k*2 + 1
h = np.zeros((kernel_size, 1))
for i in range(0 - math.ceil(sigma)*k, kernel_size - math.ceil(sigma)*k):
h[i+math.ceil(sigma)*k] = constant * math.pow(math.e, i**2/(-2*sigma_sqr))
return h
# sigma = 5 pixel (provided)
sigma = 5
# The Gaussian filter along x-axis. Its shape is (1, sz).
### Insert your code ###
h_x = gaussian_filter_1d(sigma)
# The Gaussian filter along y-axis. Its shape is (sz, 1).
### Insert your code ###
h_y = gaussian_filter_1d(sigma).T
# Visualise the filters (provided)
plt.subplot(1, 2, 1)
plt.imshow(h_x)
plt.subplot(1, 2, 2)
plt.imshow(h_y)
<matplotlib.image.AxesImage at 0x25e81612690>
2.5 Perform Gaussian smoothing ($\sigma$ = 5 pixels) using two separable filters and evaluate the computational time for separable Gaussian filtering. After that, perform Sobel filtering, show the gradient magnitude map and check whether it is the same as the previous one without separable filtering.¶
# Perform separable Gaussian smoothing and count time
start = time.time()
image_filtered_x = scipy.signal.convolve2d(image_noisy, h_x)
image_filtered = scipy.signal.convolve2d(image_filtered_x, h_y)
print("Time taken: ", time.time()-start)
# Image filtering
grad_x = scipy.signal.convolve2d(image_filtered, sobel_x)
grad_y = scipy.signal.convolve2d(image_filtered, sobel_y)
# Calculate the gradient magnitude
grad_mag2 = np.sqrt(grad_x**2 + grad_y**2)
# Display the gradient magnitude map (provided)
plt.imshow(grad_mag2, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
# Check the difference between the current gradient magnitude map
# and the previous one produced without separable filtering. You
# can report the mean difference between the two.
print(np.mean(grad_mag2-grad_mag))
Time taken: 0.3551754951477051 7.711052268278088e-15
2.6 Comment on the Gaussian + Sobel filtering results and the computational time.¶
With Gaussian filtering, the edges found are much wider and smoother than the ones found with Sobel filtering. There is also slightly less edges produced from noise in the flatter areas of the image. The reduced noise does also mean that there is less detail in the edges detected, however.
With the computational time of gaussian filtering, there is a distinct difference between convolving both directions at once as opposed to separately, with the separable filtering being around 10x faster.
3. Challenge: Implement 2D image filters using Pytorch (24 points).¶
Pytorch is a machine learning framework that supports filtering and convolution.
The Conv2D operator takes an input array of dimension NxC1xXxY, applies the filter and outputs an array of dimension NxC2xXxY. Here, since we only have one image with one colour channel, we will set N=1, C1=1 and C2=1. You can read the documentation of Conv2D for more detail.
# Import libaries (provided)
import torch
3.1 Expand the dimension of the noisy image into 1x1xXxY and convert it to a Pytorch tensor.¶
def convert_array(array : np.ndarray):
# Expand the dimension of the numpy array
expanded = np.expand_dims(array, (0,1))
# Convert to a Pytorch tensor using torch.from_numpy
return torch.from_numpy(expanded)
3.2 Create a Pytorch Conv2D filter, set its kernel to be a 2D Gaussian filter and perform filtering.¶
# A 2D Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)
# Create the Conv2D filter
torch_h = convert_array(h)
# Filtering
image_filtered = torch.conv2d(convert_array(image_noisy),torch_h)
# Display the filtering result (provided)
plt.imshow(image_filtered[0].permute(1,2,0), cmap='gray')
plt.gcf().set_size_inches(8, 8)
3.3 Implement Pytorch Conv2D filters to perform Sobel filtering on Gaussian smoothed images, show the gradient magnitude map.¶
# Create Conv2D filters
torch_sobel_x = convert_array(sobel_x).type(torch.DoubleTensor)
torch_sobel_y = convert_array(sobel_y).type(torch.DoubleTensor)
# Perform filtering
grad_x = torch.conv2d(image_filtered, torch_sobel_x)
grad_y = torch.conv2d(image_filtered, torch_sobel_y)
# Calculate the gradient magnitude map
grad_mag3 = torch.sqrt(torch.square(grad_x) + torch.square(grad_y))[0].permute(1,2,0)
# Visualise the gradient magnitude map (provided)
plt.imshow(grad_mag3, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)